package com.example.thread.day13Condition;

import java.util.concurrent.TimeUnit;

/**
 * Object对象中的wait(),notify()方法,用于线程等待和唤醒等待中的线程
 *
 */
//同步中等待和唤醒线程示例
public class Demo1 {
    static Object lock = new Object();

    public static class T extends Thread {
        @Override
        public void run() {
            System.out.println(System.currentTimeMillis() + "," + this.getName() + "准备获取锁");
            synchronized (lock) {
                System.out.println(System.currentTimeMillis() + "," + this.getName() + "获取锁成功");
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(System.currentTimeMillis() + "," + this.getName() + "释放锁成功");
        }
    }

    public static class T2 extends Thread {
        @Override
        public void run() {
            System.out.println(System.currentTimeMillis() + "," + this.getName() + "准备获取锁");
            synchronized (lock) {
                System.out.println(System.currentTimeMillis() + "," + this.getName() + "获取锁成功");
                lock.notify();
                System.out.println(System.currentTimeMillis() + "," + this.getName() + "notify!");
                try {
                    TimeUnit.SECONDS.sleep(5);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(System.currentTimeMillis() + "," + this.getName() + "准备释放锁");
            }
            System.out.println(System.currentTimeMillis() + "," + this.getName() + "释放锁成功");
        }
    }

    public static void main(String[] args) throws InterruptedException {
        T t1 = new T();
        t1.setName("t1");
        t1.start();
        TimeUnit.SECONDS.sleep(5);

        T2 t2 = new T2();
        t2.setName("t2");
        t2.start();
    }
}
